package controller;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;

import DAO.CookingDAO;
import DAO.DishDAO;
import DAO.FoodDAO;
import DTO.CookingDTO;
import DTO.DishDTO;
import DTO.FoodDTO;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import constants.StringConstants;

/**
 * Servlet implementation class AddDishServlet
 */
public class DishMaintainServlet extends HttpServlet {
	private static final String ADD_DISH_PAGE = "admin/dish-add.jsp";
	private static final String PICK_UP_FOOD = "admin/dish-pick-food.jsp";
	private static final String DISH_SERVLET = "DishServlet";

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public DishMaintainServlet() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	@Override
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		if (request.getSession().getAttribute("ADMIN_USERNAME") != null) {
			String action = request.getParameter("action");
			if (action.equals(StringConstants.ADD_DISH)) {
				CookingDAO cookingDAO = new CookingDAO();
				ArrayList<CookingDTO> list = cookingDAO.select();

				request.setAttribute("COOKINGLIST", list);
				RequestDispatcher rd = request
						.getRequestDispatcher(ADD_DISH_PAGE);
				rd.forward(request, response);
			} else if (action.equals(StringConstants.ADD_FOOD_TO_DISH)) {
				FoodDAO foodDAO = new FoodDAO();
				ArrayList<FoodDTO> list = foodDAO.select();
				request.setAttribute("FOODLIST", list);

				RequestDispatcher rd = request
						.getRequestDispatcher(PICK_UP_FOOD);
				rd.forward(request, response);
			} else if (action.equals(StringConstants.EDIT_FOOD_TO_DISH)) {
				FoodDAO foodDAO = new FoodDAO();
				ArrayList<FoodDTO> list = foodDAO.select();
				request.setAttribute("FOODLIST", list);

				// get Food in Dish
				DishDAO dishDAO = new DishDAO();
				int dishId = Integer.parseInt(request.getParameter("dishId"));
				DishDTO dishDTO = new DishDTO();
				dishDTO.setId(dishId);

				dishDAO.get(dishDTO);
				dishDAO.getFoodsInDish(dishDTO);
				request.setAttribute("DISHDTO", dishDTO);

				RequestDispatcher rd = request
						.getRequestDispatcher(PICK_UP_FOOD);
				rd.forward(request, response);
			} else {
				response.sendRedirect("error.html");
			}
		} else {
			RequestDispatcher rd = request
					.getRequestDispatcher("admin/admin-login.html");
			rd.forward(request, response);
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	@Override
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		if (request.getSession().getAttribute("ADMIN_USERNAME") != null) {
			request.setCharacterEncoding("UTF-8");
			boolean isMultipart = ServletFileUpload.isMultipartContent(request);
			if (!isMultipart) {
				String action = request.getParameter("action");
				// process for deleting
				if (action.equals(StringConstants.DELETE)) {
					int id = Integer.parseInt(request.getParameter("id"));
					DishDAO dao = new DishDAO();
					dao.delete(id);

					// String realPath = getServletContext().getRealPath("/")
					// + "img\\dish\\" + filename;
					// File savedFile = new File(realPath);
					// savedFile.delete();

					response.sendRedirect(DISH_SERVLET);
				} else {
					response.sendRedirect("error.html");
				}
			} else {
				FileItemFactory factory = new DiskFileItemFactory();
				ServletFileUpload upload = new ServletFileUpload(factory);
				upload.setHeaderEncoding("UTF-8");
				List items = null;
				try {
					items = upload.parseRequest(request);
				} catch (FileUploadException e) {
					e.printStackTrace();
				}
				Iterator iterator = items.iterator();
				Hashtable params = new Hashtable();
				String filename = null;
				FileItem imgFileItem = null;
				while (iterator.hasNext()) {
					FileItem item = (FileItem) iterator.next();
					if (item.isFormField()) {
						params.put(item.getFieldName(), item.getString());
					} else {
						imgFileItem = item;
					}
				}
				String action = (String) params.get("action");
				if (action.equals(StringConstants.ADD)) {
					try {
						// create new file img
						String itemName = imgFileItem.getName();
						filename = itemName.substring(itemName
								.lastIndexOf("\\") + 1);
						String realPath = getServletContext().getRealPath("/")
								+ "img\\dish\\" + filename;
						File savedFile = new File(realPath);
						imgFileItem.write(savedFile);
						filename = savedFile.getName();
					} catch (Exception e) {
						e.printStackTrace();
					}

					String name = (String) params.get("name");
					int calo = Integer
							.parseInt(params.get("calo").equals("") ? "0"
									: params.get("calo").toString());
					int cookingId = Integer
							.parseInt(params.get("cookingId") == null ? "0"
									: params.get("cookingId").toString());
					String description = (String) params.get("description");

					CookingDTO cooking = new CookingDTO();
					cooking.setId(cookingId);

					DishDTO dish = new DishDTO(0, name, calo, cooking,
							description, "img\\dish\\" + filename);
					DishDAO dao = new DishDAO();
					try {
						dao.add(dish);
					} catch (Exception e) {
						// delete file img when add fail
						String realPath = getServletContext().getRealPath("/")
								+ "img\\dish\\" + filename;
						File savedFile = new File(realPath);
						savedFile.delete();

						e.printStackTrace();
					}
					// proccess add Food in Dish
					int dishId = dish.getId();
					String selectedFoods_str = request
							.getParameter("foods_str");
					String[] selectedFoods_id = selectedFoods_str.split(",");
					ArrayList<Integer> selectedFoods = new ArrayList<Integer>();
					for (String foodId_str : selectedFoods_id) {
						selectedFoods.add(Integer.parseInt(foodId_str));
					}
					dao.addDishFood(selectedFoods, dishId);

					response.sendRedirect("DishServlet");
				} else if (action.equals(StringConstants.CHANGE)) {
					if (imgFileItem != null) {
						try {
							// if update img, create new file and delete old img
							String itemName = imgFileItem.getName();
							filename = itemName.substring(itemName
									.lastIndexOf("\\") + 1);
							String realPath = getServletContext().getRealPath(
									"/")
									+ "img\\dish\\" + filename;
							File savedFile = new File(realPath);
							imgFileItem.write(savedFile);
							filename = savedFile.getName();

							String oldFilePath = (String) params.get("oldImg");
							realPath = getServletContext().getRealPath("/")
									+ oldFilePath;
							File deletedFile = new File(realPath);
							deletedFile.delete();
						} catch (Exception e) {
							e.printStackTrace();
						}
					}

					int id = Integer.parseInt(params.get("id") == null ? "0"
							: params.get("id").toString());
					String name = (String) params.get("name");
					int calo = Integer
							.parseInt(params.get("calo") == null ? "0" : params
									.get("calo").toString());
					int cookingId = Integer
							.parseInt(params.get("cookingId") == null ? "0"
									: params.get("cookingId").toString());
					String description = (String) params.get("description");

					CookingDTO cooking = new CookingDTO();
					cooking.setId(cookingId);

					DishDTO dish = new DishDTO(id, name, calo, cooking,
							description, "img\\dish\\" + filename);
					DishDAO dao = new DishDAO();

					try {
						dao.update(dish);
					} catch (Exception e) {
						// delete file img when add fail
						String realPath = getServletContext().getRealPath("/")
								+ "img\\dish\\" + filename;
						File savedFile = new File(realPath);
						savedFile.delete();

						e.printStackTrace();
					}
					// proccess edit Food in Dish
					String selectedFoods_str = (String) params.get("foods_str");
					String[] selectedFoods_id = selectedFoods_str.split(",");
					ArrayList<Integer> selectedFoods = new ArrayList<Integer>();
					for (String foodId_str : selectedFoods_id) {
						if (!foodId_str.equals("")) {
							selectedFoods.add(Integer.parseInt(foodId_str));
						}
					}
					dao.addDishFood(selectedFoods, id);

					response.sendRedirect(DISH_SERVLET);
				}
			}
		} else {
			RequestDispatcher rd = request
					.getRequestDispatcher("admin/admin-login.html");
			rd.forward(request, response);
		}
	}
}
